package ace.j2se.l2;

import java.io.File;
import java.net.ConnectException;
import java.util.Date;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

/* 
 *需要安装liboffice 
 * cd C:\Program Files\OpenOffice.org 3\program
 * soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
 */

public class JOD4DocToPDF {

	public void docToPdf(File inputFile, File outputFile) {
		Date start = new Date();
		// connect to an OpenOffice.org instance running on port 8100
		OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
		try {
			connection.connect();

			// convert
			DocumentConverter converter = new OpenOfficeDocumentConverter(
					connection);
			converter.convert(inputFile, outputFile);
		} catch (ConnectException cex) {
			cex.printStackTrace();
		} finally {
			// close the connection
			if (connection != null) {
				connection.disconnect();
				connection = null;
			}
		}
		long l = (start.getTime() - new Date().getTime());
		long day = l / (24 * 60 * 60 * 1000);
		long hour = (l / (60 * 60 * 1000) - day * 24);
		long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
		long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		System.out.println("生成" + outputFile.getName() + "耗费：" + min + "分" + s
				+ "秒");
	}

	class TestThread extends java.lang.Thread {
		public File inputFile;
		public File outputFile;

		public void run() {
			JOD4DocToPDF t = new JOD4DocToPDF();
			t.docToPdf(inputFile, outputFile);
			System.out.println(outputFile.getName() + "文件已生成");
		}
	}

	public void test() {
		TestThread t1 = new TestThread();
		t1.inputFile = new File("d:/11.doc");
		t1.outputFile = new File("d:/11.pdf");

		 TestThread t2 = new TestThread();
		 t2.inputFile = new File("d:/22.xls");
		 t2.outputFile = new File("d:/22.pdf");
		//
		// TestThread t3 = new TestThread();
		// t3.inputFile = new File("d:/33.doc");
		// t3.outputFile = new File("d:/33.pdf");

		t2.start();
		t1.start();
		// t3.start();
	}

	public static void main(String[] args) throws Exception {
		JOD4DocToPDF p = new JOD4DocToPDF();
		p.test();
	}

}
